import Vue from "vue";
import VueRouter from "vue-router";
import { Loading } from "element-ui";

Vue.use(VueRouter);

import { Message } from "element-ui";

import store from "@/store";

import currencyRoutes from "./modules/currencyRoutes";

const router = new VueRouter({
  routes: currencyRoutes
  // scrollBehavior() {
  //   return { x: 0, y: 0 }
  // }
});

// 解决Vue-Router升级导致的Uncaught(in promise) navigation guard问题
// https://www.jianshu.com/p/1e462d9b0c03
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch(err => err);
};

// 导航守卫
router.beforeEach(async (to, from, next) => {
  if (store.getters.token) {
    if (to.path === "/login") {
      next(false);
    } else {
      // 浏览器tab名设置
      document.title = `${to.meta.title}—${process.env.VUE_APP_APP_NAME}`;
      const permission = store.getters.permission;
      if (permission) {
        to.matched.length &&
          store.dispatch("Layout/saveActivePage", to.matched);
        next();
      } else {
        // 显示加载动画，避免白屏体验
        const loading = Loading.service();
        await store.dispatch("user/getUserInfo");
        to.matched.length &&
          store.dispatch("Layout/saveActivePage", to.matched);
        loading.close();
        next({ ...to, replace: true });
      }
    }
  } else {
    to.path === "/login"
      ? next()
      : next({ path: "/login", query: { redirect: to.fullPath } });
  }
});

export default router;
